package com.gyg.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * <des>
 *
 * <des>
 *
 * @create Date 2021-10-25
 **/
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String,String>  redisTemplate;


    public boolean set(String k,String v){
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                redisConnection.set(serializer.serialize(k),serializer.serialize(v));
                //七天后过期
                redisConnection.expire(serializer.serialize(k),60*60*24*7);
                return true;
            }
        });
                return result;
    }

    public String get(String k){
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value = redisConnection.get(serializer.serialize(k));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    public Long del(String k){
        Long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                return redisConnection.del(serializer.serialize(k));

            }
        });
        return result;
    }

    public Set<String> getKeys(){
        Set<String>  result = redisTemplate.execute(new RedisCallback<Set<String> >() {
            @Override
            public Set<String>  doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                Set<byte[]> keys = redisConnection.keys(serializer.serialize("*"));
                Set<String> keySet = new HashSet<>();
                for (byte[] b: keys){
                    keySet.add(serializer.deserialize(b));
                }
                return keySet;
            }
        });
        return result;
    }
}
